<template>
    <div>
        <el-button type="primary" @click="newTeamDialogVisible = true">{{$t('team.add')}}</el-button>
        <el-table :data="teamList" style="width: 100%" stripe v-loading="teamList === null">
            <el-table-column width="80" prop="ID" label="ID"/>
            <el-table-column width="80" prop="Logo" :label="$t('team.logo')">
                <template v-slot="scope">
                    <el-image style="width: 50px; height: 50px" :src="utils.baseURL + '/uploads/' + scope.row.Logo"
                              fit="fill"/>
                </template>
            </el-table-column>

            <el-table-column prop="Name" :label="$t('team.team_name')"/>
            <el-table-column prop="Score" :label="$t('team.score')" :formatter="(row) => utils.FormatFloat(row.Score)"/>
            <el-table-column width="300" prop="SecretKey" label="Token"/>
            <el-table-column :label="$t('general.create_at')" width="200"
                             :formatter="(row)=>utils.FormatGoTime(row.CreatedAt)"/>
            <el-table-column :label="$t('general.update_at')" width="200"
                             :formatter="(row)=>utils.FormatGoTime(row.UpdatedAt)"/>
            <el-table-column :label="$t('general.operate')">
                <template v-slot="scope">
                    <el-button
                            size="small"
                            @click="()=>{Object.assign(editTeamForm, JSON.parse(JSON.stringify(scope.row))); editTeamDialogVisible = true}">
                        {{$t('general.edit')}}
                    </el-button>

                    <el-popconfirm
                            :confirmButtonText="$t('general.confirm_cancel')"
                            :cancelButtonText="$t('general.cancel')"
                            icon="el-icon-info"
                            iconColor="red"
                            :title="$t('team.delete_confirm')"
                            @confirm="handleDelete(scope.row)"
                    >
                    <template #reference>
                        <el-button size="small" type="danger">{{$t('general.delete')}}</el-button>
                    </template>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>

        <!-- New team -->
        <el-dialog :title="$t('team.add')" v-model="newTeamDialogVisible">
            <el-button @click="newTeamForm.push({Name: '',Logo: ''})">{{$t('team.new')}}</el-button>
            <el-divider/>
            <div v-for="(item, index) in newTeamForm" v-bind:key="index">
                <el-row :gutter="20">
                    <el-form :model="item" label-width="80px">
                        <el-button type="danger" icon="el-icon-delete" circle @click="newTeamForm.splice(index, 1)"/>
                        <el-col :span="10">
                            <el-form-item :label="$t('team.team_name')">
                                <el-input v-model="item.Name"/>
                                <el-input v-model="item.Logo" size="small" :placeholder="$t('team.picture_url')"/>
                            </el-form-item>
                        </el-col>
                        <el-col :span="10">
                            <el-form-item :label="$t('team.team_logo')">
                                <el-upload name="picture" :action="utils.baseURL + '/manager/uploadPicture'"
                                           :headers="{'Authorization': token}"
                                           :on-success="(response) => {newTeamForm[index].Logo = response.data}">
                                    <el-button size="small" type="primary">{{$t('team.upload')}}</el-button>
                                    <div slot="tip" class="el-upload__tip">{{$t('team.file_limit')}}</div>
                                </el-upload>
                            </el-form-item>
                        </el-col>
                    </el-form>
                </el-row>
            </div>
            <el-button type="primary" @click="onNewTeams">{{$t('team.add')}}</el-button>
        </el-dialog>

        <!-- Edit team -->
        <el-dialog :title="$t('team.edit')" v-model="editTeamDialogVisible">
            <el-form label-width="80px">
                <el-form-item :label="$t('team.team_name')">
                    <el-input v-model="editTeamForm.Name"/>
                    <el-input v-model="editTeamForm.Logo" size="small" :placeholder="$t('team.picture_url')"/>
                </el-form-item>
                <el-form-item :label="$t('team.team_logo')">
                    <el-upload name="picture" :action="utils.baseURL + '/manager/uploadPicture'"
                               :headers="{'Authorization': token}"
                               :on-success="(response) => {editTeamForm.Logo = response.data}">
                        <el-button size="small" type="primary">{{$t('team.upload')}}</el-button>
                        <div slot="tip" class="el-upload__tip">{{$t('team.file_limit')}}</div>
                    </el-upload>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="onEditTeam">{{$t('team.edit')}}</el-button>
                    <el-popconfirm
                            :title="$t('team.reset_password_confirm')"
                            :confirmButtonText="$t('general.apply')"
                            :cancelButtonText="$t('general.cancel')"
                            @confirm="onResetPassword(editTeamForm.ID)"
                    >
                        <template #reference>
                        <el-button>{{$t('team.reset_password')}}</el-button>
                        </template>
                    </el-popconfirm>
                </el-form-item>
            </el-form>
        </el-dialog>

    </div>
</template>

<script setup>
import { ref, reactive, onMounted, h } from 'vue'
import { getCurrentInstance } from 'vue';
import { useI18n } from 'vue-i18n';
import utils from '@/utils.js'
const { proxy } = getCurrentInstance()
const { t } = useI18n()

const teamList = ref(null)
const newTeamDialogVisible = ref(false)
const editTeamDialogVisible = ref(false)

let token = localStorage.getItem('managerToken')

const newTeamForm = reactive([{
                Name: '',
                Logo: '',
            }])

const editTeamForm = reactive({
                Name: '',
                Logo: '',
            })
        

onMounted(() => {
            getTeams()
        })


function getTeams() {
                utils.GET("/manager/teams").then(res => {
                    teamList.value = res
                }).catch(err => proxy.$message.error(err))
            }

function onNewTeams() {
                utils.POST('/manager/teams', newTeamForm).then(res => {
                    newTeamDialogVisible.value = false
                    getTeams()
                    // Clean form
                    Object.assign(newTeamForm, [{
                        Name: '',
                        Logo: '',
                    }])

                    
                    var password = [h('p', null, t('team.save_password'))]
                    res.forEach(item => {
                        password.push(h('p', null, t('team.account_detail', {
                            Name: item.Name,
                            Password: item.Password
                        })))
                    })

                    proxy.$alert(h('p', null, password), t('team.team_password'), {
                        confirmButtonText: t('team.save_confirm')
                    });
                }).catch(err => proxy.$message({message: err, type: 'error'}))
            }

function onEditTeam() {
                utils.PUT('/manager/team', editTeamForm).then(res => {
                    editTeamDialogVisible.value = false
                    getTeams()
                    proxy.$message.success(res)
                }).catch(err => proxy.$message({message: err, type: 'error'}))
            }

function onResetPassword(teamID) {
                utils.POST('/manager/team/resetPassword', {
                    ID: teamID
                }).then(res => {
                    editTeamDialogVisible.value = false
                    proxy.$alert(res, t('team.new_password'), {
                        confirmButtonText: t('general.apply')
                    })
                }).catch(err => proxy.$message({message: err, type: 'error'}))
            }

function handleDelete(row) {
                utils.DELETE("/manager/team?id=" + row.ID).then(res => {
                    proxy.$message({
                        message: res,
                        type: 'success'
                    });
                    getTeams()
                }).catch(err => {
                    proxy.$message({
                        message: err,
                        type: 'error'
                    });
                })
            }
</script>

<style scoped>

</style>